package com.martin.lib_base.ktx

import android.app.Activity
import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.lifecycleScope
import dev.DevUtils
import kotlinx.coroutines.CoroutineScope

/**
 * @author：Houge
 * @date：2022/11/11
 * @desc：Context拓展
 */

/**
 * 根据Context来关闭Activity
 */
fun Context.finish() {
    if (this is Activity) {
        this.finish()
    } else {
        DevUtils.getTopActivity().finish()
    }
}

/**
 * 获取context对应的Activity
 */
fun Context.getActivity(): Activity? {
    if (this is Activity) {
        return this
    } else if (this is Fragment) {
        return requireActivity()
    }
    return null
}

/**
 * 获取生命周期持有者
 */
fun Context.getLifecycleOwner(): LifecycleOwner {
    return when (this) {
        is LifecycleOwner -> {
            this
        }

        else -> {
            return DevUtils.getTopActivity() as LifecycleOwner
        }
    }
}

/**
 * 获取CoroutineScope
 */
fun Context.getScope(): CoroutineScope {
    return getLifecycleOwner().lifecycleScope
}